import serial
import sys
def parse_serial_data(data_str):
    """解析单行16进制数据并转换为十进制"""
    result = {}
    try:
        pairs = data_str.strip().split(',')
        for pair in pairs:
            key, value = pair.split(':')
            # 将4位16进制字符串转换为十进制整数
            hex_value = int(value, 16)

            # 补码转换：如果是负数，减去 2^16
            if hex_value & 0x8000:  # 检查最高位是否为1
                dec_value = hex_value - 0x10000
            else:
                dec_value = hex_value

            result[key] = dec_value
    except ValueError as e:
        print(f"数据解析错误: {e}")
    return result

def main():
    # 配置串口参数（根据实际情况修改）
    serial_port = 'COM13'  # 例如 '/dev/ttyUSB0' 或 'COM1'
    baud_rate = 9600
    
    try:
        with serial.Serial(serial_port, baud_rate, timeout=1) as ser:
            print(f"已连接到 {serial_port}，等待数据...")
            while True:
                # 读取一行数据（以换行符结束）
                line = ser.readline().decode('utf-8').strip()
                if line:
                    parsed_data = parse_serial_data(line)
                    if parsed_data:
                        # 格式化输出结果
                        # 构造输出字符串
                        output = " | ".join([f"{k}: {v}" for k, v in parsed_data.items()])
                        # 使用 \r 覆盖当前行内容
                        sys.stdout.write("\r" + output)
                        sys.stdout.flush()
    except serial.SerialException as e:
        print(f"串口错误: {e}")
    except KeyboardInterrupt:
        print("程序已终止")

if __name__ == '__main__':
    main()